import { useUserStore } from '@/stores/user'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'Dashboard'
        }
      },
      // 内容管理
      {
        path: '/content',
        name: 'Content',
        meta: {
          title: '内容',
          icon: 'Document'
        },
        children: [
          {
            path: '/content/article',
            name: 'Article',
            component: () => import('@/views/content/article/index.vue'),
            meta: {
              title: '文章管理',
              icon: 'Document'
            }
          },
          {
            path: '/content/article/edit',
            name: 'ArticleAdd',
            component: () => import('@/views/content/article/edit.vue'),
            meta: {
              title: '新建文章',
              hidden: true
            }
          },
          {
            path: '/content/article/edit/:id',
            name: 'ArticleEdit',
            component: () => import('@/views/content/article/edit.vue'),
            meta: {
              title: '编辑文章',
              hidden: true
            }
          },
          {
            path: '/content/channel',
            name: 'Channel',
            component: () => import('@/views/content/channel/index.vue'),
            meta: {
              title: '栏目管理',
              icon: 'Menu'
            }
          },
          {
            path: '/content/block',
            name: 'Block',
            component: () => import('@/views/content/block/index.vue'),
            meta: {
              title: '区块管理',
              icon: 'Grid'
            }
          },
          {
            path: '/content/block/content/:id',
            name: 'BlockContent',
            component: () => import('@/views/content/block/content.vue'),
            meta: {
              title: '区块内容管理',
              hidden: true
            }
          },
          {
            path: '/content/generate',
            name: 'Generate',
            component: () => import('@/views/system/generate/index.vue'),
            meta: {
              title: '生成管理',
              icon: 'Lightning'
            }
          },
          {
            path: '/content/static-files',
            name: 'StaticFiles',
            component: () => import('@/views/system/static-files/index.vue'),
            meta: {
              title: '静态文件管理',
              icon: 'FolderOpened'
            }
          },
          {
            path: '/content/attachment',
            name: 'Attachment',
            component: () => import('@/views/content/attachment/index.vue'),
            meta: {
              title: '附件管理',
              icon: 'Paperclip'
            }
          }
        ]
      },
      // 文件管理
      {
        path: '/files',
        name: 'Files',
        meta: {
          title: '文件',
          icon: 'Folder'
        },
        children: [
          {
            path: '/files/template',
            name: 'TemplateFile',
            component: () => import('@/views/system/template-file/index.vue'),
            meta: {
              title: '模板文件管理',
              icon: 'Document'
            }
          },
          {
            path: '/files/backup',
            name: 'TemplateBackup',
            component: () => import('@/views/files/backup/index.vue'),
            meta: {
              title: '模板文件备份',
              icon: 'Download'
            }
          }
        ]
      },
      // 配置管理
      {
        path: '/config',
        name: 'Config',
        meta: {
          title: '配置',
          icon: 'Setting'
        },
        children: [
          {
            path: '/config/site',
            name: 'Site',
            component: () => import('@/views/content/site/index.vue'),
            meta: {
              title: '站点设置',
              icon: 'OfficeBuilding'
            }
          },
          {
            path: '/config/model',
            name: 'Model',
            component: () => import('@/views/system/model/index.vue'),
            meta: {
              title: '模型管理',
              icon: 'Grid'
            }
          },
          {
            path: '/config/block',
            name: 'BlockConfig',
            component: () => import('@/views/config/block/index.vue'),
            meta: {
              title: '区块设置',
              icon: 'Grid'
            }
          }
        ]
      },
      // 系统管理
      {
        path: '/system',
        name: 'System',
        meta: {
          title: '系统',
          icon: 'Setting'
        },
        children: [
          {
            path: '/system/user',
            name: 'User',
            component: () => import('@/views/system/user/index.vue'),
            meta: {
              title: '用户管理',
              icon: 'User'
            }
          },
          {
            path: '/system/theme',
            name: 'Theme',
            component: () => import('@/views/system/theme/index.vue'),
            meta: {
              title: '主题管理',
              icon: 'Brush'
            }
          },
          {
            path: '/system/static',
            name: 'Static',
            component: () => import('@/views/system/static/index.vue'),
            meta: {
              title: '静态文件',
              icon: 'Folder'
            }
          }
        ]
      }
    ]
  },
  // 在 routes 数组中添加示例页面路由
  {
    path: '/examples/upload',
    name: 'UploadExamples',
    component: () => import('@/views/examples/upload-examples.vue'),
    meta: {
      title: '文件上传示例',
      requiresAuth: true // 根据需要设置是否需要登录
    }
  },
  {
    path: '/examples/carousel',
    name: 'ArticleCarouselDemo',
    component: () => import('@/views/examples/article-carousel-demo.vue'),
    meta: {
      title: '文章轮播示例',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('路由守卫:', from.path, '->', to.path)

  try {
    // 特殊处理：从生成管理页面离开
    if (from.path === '/content/generate' && to.path !== '/content/generate') {
      console.log('检测到从生成管理页面离开，清理状态...')

      // 清理可能的阻塞状态
      if (window.__generatePageLoading) {
        console.log('清理生成页面加载状态')
        window.__generatePageLoading = false
      }

      // 强制清理，确保路由能够正常工作
      setTimeout(() => {
        console.log('延迟清理完成，继续路由跳转')
      }, 0)
    }

    const userStore = useUserStore()

    if (to.meta.requiresAuth && !userStore.token) {
      console.log('需要登录，跳转到登录页')
      next('/login')
    } else if (to.path === '/login' && userStore.token) {
      console.log('已登录，跳转到首页')
      next('/')
    } else {
      console.log('路由守卫通过')
      next()
    }
  } catch (error) {
    console.error('路由守卫错误:', error)
    // 即使出错也要继续路由跳转
    next()
  }
})

// 路由后置守卫
router.afterEach((to, from) => {
  console.log('路由跳转完成:', from.path, '->', to.path)
})

// 路由错误处理
router.onError(error => {
  console.error('路由错误:', error)
  // 路由错误时尝试重新跳转
  if (error.message.includes('Navigation cancelled')) {
    console.log('导航被取消，尝试重新跳转')
  }
})

export default router
